package com.yuanren.em.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuanren.em.constants.Constants;
import com.yuanren.em.entity.Good;
import com.yuanren.em.entity.Order;
import com.yuanren.em.entity.OrderGoods;
import com.yuanren.em.entity.OrderItem;
import com.yuanren.em.exception.ServiceException;
import com.yuanren.em.mapper.GoodMapper;
import com.yuanren.em.mapper.OrderGoodsMapper;
import com.yuanren.em.mapper.OrderMapper;
import com.yuanren.em.mapper.StandardMapper;
import com.yuanren.em.utils.TokenUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

import static com.yuanren.em.constants.RedisConstants.GOOD_TOKEN_KEY;

@Service
public class OrderService extends ServiceImpl<OrderMapper, Order> {

    @Resource
    private OrderMapper orderMapper;
    @Resource
    private OrderGoodsMapper orderGoodsMapper;
    @Resource
    private StandardMapper standardMapper;
    @Resource
    private GoodMapper goodMapper;
    @Resource
    private CartService cartService;
    @Resource
    private RedisTemplate<String, Good> redisTemplate;

    @Transactional
    public String saveOrder(Order order) {
        order.setUserId(TokenUtils.getCurrentUser().getId());
        String orderNo = DateUtil.format(new Date(), "yyyyMMddHHmmss") + RandomUtil.randomNumbers(6);
        order.setOrderNo(orderNo);
        order.setCreateTime(DateUtil.now());
        // 持久化cartIds到数据库
        System.out.println("下单时cartIds: " + order.getCartIds());
        if (order.getCartIds() != null && !order.getCartIds().isEmpty()) {
            String cartIdsStr = order.getCartIds().stream().map(String::valueOf).collect(java.util.stream.Collectors.joining(","));
            order.setCartIdsStr(cartIdsStr);
            System.out.println("设置cartIdsStr: " + cartIdsStr);
        } else {
            System.out.println("cartIds为空，不设置cartIdsStr");
        }
        orderMapper.insert(order);

        //遍历order里携带的goods数组，并用orderItem对象来接收
        String goods = order.getGoods();
        List<OrderItem> orderItems = JSON.parseArray(goods, OrderItem.class);
        for (OrderItem orderItem : orderItems) {
            OrderGoods orderGoods = new OrderGoods();
            orderGoods.setOrderId(order.getId());
            long good_id = orderItem.getId();
            String standard = orderItem.getStandard();
            int num = orderItem.getNum();
            orderGoods.setGoodId(good_id);
            orderGoods.setCount(num);
            orderGoods.setStandard(standard);
            //插入到order_good表
            orderGoodsMapper.insert(orderGoods);
        }
        // 注意：购物车在支付时清除，下单时不清除
        return orderNo;
    }

    //给订单付款
    @Transactional
    public void payOrder(String orderNo) {
        //更改状态为已支付
        orderMapper.payOrder(orderNo);
        
        //获取订单信息
        LambdaQueryWrapper<Order> orderLambdaQueryWrapper = new LambdaQueryWrapper<>();
        orderLambdaQueryWrapper.eq(Order::getOrderNo, orderNo);
        Order order = getOne(orderLambdaQueryWrapper);
        if (order == null) {
            throw new ServiceException(Constants.CODE_500, "订单不存在");
        }
        
        //获取订单中的所有商品
        List<Map<String, Object>> orderGoodsList = orderMapper.selectByOrderNo(orderNo);
        
        //处理每个商品的库存和销量
        for (Map<String, Object> orderGoods : orderGoodsList) {
            int count = (int) orderGoods.get("count");
            Object goodIdObj = orderGoods.get("goodId");
            Long goodId = null;
            if(goodIdObj instanceof Long) {
                goodId = (Long) goodIdObj;
            } else if(goodIdObj != null) {
                try {
                    goodId = Long.parseLong(goodIdObj.toString());
                } catch (NumberFormatException e) {
                    throw new ServiceException(Constants.CODE_500, "商品ID不正确");
                }
            }

            if(goodId == null) {
                throw new ServiceException(Constants.CODE_500, "商品ID不存在");
            }
            
            String standard = (String) orderGoods.get("standard");
            int store = standardMapper.getStore(goodId, standard);
            if (store < count) {
                throw new ServiceException(Constants.CODE_500, "商品 " + goodId + " 库存不足");
            }
            standardMapper.deductStore(goodId, standard, store - count);

            //给对应商品加销量和销售额
            BigDecimal totalPrice = order.getTotalPrice();
            goodMapper.saleGood(goodId, count, totalPrice);

            // redis 增销量
            String redisKey = GOOD_TOKEN_KEY + goodId;
            ValueOperations<String, Good> valueOperations = redisTemplate.opsForValue();
            Good good = valueOperations.get(redisKey);
            if(!ObjectUtils.isEmpty(good)) {
                good.setSales(good.getSales() + count);
                valueOperations.set(redisKey, good);
            }
        }
        // 支付成功后清除购物车
        System.out.println("订单cartIdsStr: " + order.getCartIdsStr());
        System.out.println("订单cartIds: " + order.getCartIds());
        
        if (order.getCartIds() != null && !order.getCartIds().isEmpty()) {
            System.out.println("开始清除购物车，共" + order.getCartIds().size() + "个商品");
            for (Long cartId : order.getCartIds()) {
                System.out.println("清除购物车ID: " + cartId);
                cartService.removeById(cartId);
            }
        } else {
            System.out.println("购物车ID为空，无法清除");
        }
    }

    public List<Map<String, Object>> selectByUserId(int userId) {
        return orderMapper.selectByUserId(userId);
    }

    public boolean receiveOrder(String orderNo) {
        return orderMapper.receiveOrder(orderNo);
    }

    public List<Map<String, Object>> selectByOrderNo(String orderNo) {
        return orderMapper.selectByOrderNo(orderNo);
    }

    public void delivery(String orderNo) {
        LambdaUpdateWrapper<Order> orderLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        orderLambdaUpdateWrapper.eq(Order::getOrderNo, orderNo)
                .set(Order::getState, "已发货");
        update(orderLambdaUpdateWrapper);
    }
}
